"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 功能测试
Case Name   : substrb函数入参为汉字(数据库使用的字符编码为UTF8)
Create At   : 2022/09/28
@zou_jialiang0501120111
Description :
    1.调用substrb函数且入参为中文字符（数据库字符编码方式非UTF8）
    2.创建字符编码方式为utf8的数据库
    3.在编码方式为utf8的数据库上调用substrb函数入参为汉字
    4.清理环境
Expect      :
    1.失败
    2.成功
    3.成功
    4.成功
History     :
"""

import os
import unittest
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class SQL(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f'-----{os.path.basename(__file__)} start-----')
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.database = 'db_substrb_0004'
        self.Constant = Constant()


    def test_reindex(self):
        step1 = '--step1:调用substrb函数且入参为中文字符;expect:合理报错--'
        self.logger.info(step1)
        substrb_1 = self.primary_sh.execut_db_sql(
            f'''set client_encoding=UTF8;select substrb('中国人',2,7);''')
        self.logger.info(substrb_1)
        self.assertIn('ERROR', substrb_1, "执行失败" + step1)

        step2 = '--step2:创建字符编码方式为utf8的数据库;expect:成功--'
        self.logger.info(step2)
        create_database = self.primary_sh.execut_db_sql(
            f'''drop database if exists {self.database};
                create database {self.database} encoding='UTF8';''', )
        self.logger.info(create_database)
        self.assertIn(self.Constant.CREATE_DATABASE_SUCCESS, create_database,
                      "执行失败" + step2)

        step3 = '--step3:在编码方式为utf8的数据库上调用substrb函数入参为汉字;expect:成功--'
        self.logger.info(step3)
        sql_cmd = f'''select col1 from wdr_xdb_query('dbname={self.database}',
                     'select substrb(''中国人'',2,7);') as dd(col1 varchar);'''
        substrb_2 = self.primary_sh.execut_db_sql(sql_cmd)
        self.logger.info(substrb_2)
        self.assertIn('国', substrb_2, "执行失败" + step3)

    def tearDown(self):
        step4 = '--step4:清理环境;expect:成功--'
        self.logger.info(step4)
        clean_environment = self.primary_sh.execut_db_sql(
            f'''drop database {self.database};''')
        self.logger.info(clean_environment)
        self.assertIn(self.Constant.DROP_DATABASE_SUCCESS, clean_environment,
                      "执行失败" + step4)
        self.logger.info(f'-----{os.path.basename(__file__)} end-----')
